<template>
  <!-- 手动定位 -->
  <div>
    <el-dialog
      class="addr-hand-check-win"
      title="手动定位"
      :visible.sync="visible"
      :close-on-click-modal="false"
      :before-close="onOk"
      :width="`${width + 40}px`"
    >
      <div class="wrapper" :style="`width: ${width}px;height: ${height}px`">
        <div
          class="top"
        >手动定位: {{$store.state.currentTargetAddrInfo ? $store.state.currentTargetAddrInfo.target_address : ''}}</div>
        <div class="content">
          <div class="map">
            <bs-com-map
              style="height:100%;"
              vid="10087"
              :zoom="zoom"
              :zooms="[3,18]"
              :center="centerPoint"
              :editable="editable"
              @click="getPosition"
            >
              <div v-for="item in searchResult" :key="item.id">
                <map-marker
                  :position="item.point"
                  :offset="[0,0]"
                  @click="(e) => selectOneAddr(item, e)"
                  :editable="false"
                ></map-marker>
                <map-infowindow :content="getContent(item)" :position="item.point"></map-infowindow>
              </div>
              <map-poipicker input="searchInp" @complete="poipicker"></map-poipicker>
            </bs-com-map>
          </div>
          <div class="left_search">
            <el-input
              v-model="keyword"
              size="mini"
              placeholder="请输入关键词"
              style="margin-bottom: 10px;"
              class="search-inp"
              prefix-icon="el-icon-search"
              clearable
              id="searchInp"
            >
            </el-input>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 合并预览 dialog addrMergePreWinShow -->
    <div v-if="addrMergePreWinShow">
      <addrMergePreWin
        :visible.sync="addrMergePreWinShow"
        :onOk="(e) => closeDialog('addrMergePreWinShow', e)"
        :toggleAlert="(e) => { showMergeSuccess = e }"
        :showAlert="showMergeSuccess"
        :addrInfo="addrInfo"
      ></addrMergePreWin>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import addrMergePreWin from "../addrCollect/addrMergePreWin.vue";
import location from "@/icons/location.png";

import tooltip from "../../tooltips/index";

import mapicon from "@/icons/location.png";
import mapicon_on from "@/icons/mapicon_on.svg";

export default {
  components: {
    tooltip,
    addrMergePreWin,
  },
  props: {
    visible: Boolean,
    onOk: Function,
    confirmSubmit: Function,
  },
  data() {
    return {
      mapicon,
      mapicon_on,
      location,
      proportion: "",
      zoom: "",

      width: 0,
      height: 0,
      keyword: "",
      searchResult: [],
      centerPoint: [121.511096, 31.301256],

      // 地图相关
      editable: {
        type: "", // polygon | marker
        style: {
          // 非必填
          polygon: {
            strokeStyel: "solid",
            strokeColor: "#129999",
            strokeOpacity: 1,
            strokeWeight: 1,
            fillColor: "#129999",
            fillOpacity: 0.2,
          },
        },
        isAdsorb: false, // 是否吸附
        adsorbRange: 1000, // 吸附范围，单位：像素
      },
      addrMergePreWinShow: false,
      showMergeSuccess: false,
      addrInfo: null,
    };
  },
  methods: {
    getPosition(a, b, c) {
      console.log(a, b, c);
    },
    getStandAddr(poi){
      if (poi.pname && poi.cityname && poi.adname) {
        return (poi.pname || '') + (poi.cityname || '') + (poi.adname || '') + (poi.address || '') + (poi.name || '')
      }else{
        return (poi.district || '') + (poi.address || '') + (poi.name || '')
      }
    },
    poipicker(e){
      console.log(e, 'poipicker');
      this.searchResult = [{
        id: e.extData.poi.id,
        addr: e.extData.poi.name,
        // standAddr: e.extData.poi.pname || '' + e.extData.poi.cityname || '' + e.extData.poi.adname || '' +  e.extData.poi.address || '',
        standAddr: this.getStandAddr(e.extData.poi),
        detailaddr: e.extData.poi.address,
        point: e.extData.poi.location && [e.extData.poi.location.lng, e.extData.poi.location.lat],
        isCheck: false,
      }]
      this.selectOneAddr(this.searchResult[0])
    },
    getContent(item){
      let parentDiv = document.createElement('div')
      parentDiv.className = 'parentdiv_cls'

      let addrNode = document.createElement('div')
      let standAddrNode = document.createElement('div')
      let posiNode = document.createElement('div')
      addrNode.innerText = '地址名：' + item.addr
      standAddrNode.innerText = '标准地址：' + item.standAddr
      posiNode.innerText = '坐标:' + item.point[0] + ',' + item.point[1]


      let btnNode = document.createElement('button')
      btnNode.innerText = '选择此地址'
      btnNode.className = 'choose_btn_cls'
      btnNode.addEventListener('click', () => {
        this.$confirm('确认要选择此地址吗？', '提示').then(()=>{
          this.chooseCurrentAddr(item)
        }).catch(()=>{return})
      })
      parentDiv.appendChild(addrNode)
      parentDiv.appendChild(standAddrNode)
      parentDiv.appendChild(posiNode)
      parentDiv.appendChild(btnNode)
      return parentDiv
    },
    async chooseCurrentAddr(item) {
      const res1 = await this.axios.post(this.apis.addressDataUpdateStandardAddress, {
        target_address: this.$store.state.currentTargetAddrInfo && this.$store.state.currentTargetAddrInfo.target_address || undefined,
        standard_address: item.standAddr,
        lng: item.point[0],
        lat: item.point[1]
      });
      if (res1.retCode === 2000) {
        this.$message({
          message: '标准地址确认成功!',
          type: 'success',
          customClass: 'messageBox'
        });

        this.$parent.$parent.$emit('addrSureCallback')
        this.$parent.positioningManualWinShow = false
      }else{
        this.$message({
          message: res1.retMessage,
          type: 'warning',
          customClass: 'messageBox'
        });
      }

      const res = await this.axios.post(this.apis.addressDataQuery, {
        page: 1,
        limit: 10,
        standard_address:  item.standAddr,
        import_file_record_id: this.$store.state.currentFileInfo.id,
        no_eq_target_address: this.$store.state.currentTargetAddrInfo.target_address
      });
      if (res.rows.items.length <= 0) {
        return
      }
      this.addrMergePreWinShow = true;
      this.$parent.positioningManualWinShow = false
      this.addrInfo = item;
    },
    closeDialog(dialogStr) {
      this[dialogStr] = false;
    },
    initScreensize() {
      // let proportion = document.documentElement.clientWidth / document.documentElement.clientHeight
      let proportion = 1532 / 792;
      this.width = parseInt(document.documentElement.clientWidth * 0.9);
      this.height = parseInt(this.width / proportion);
      console.log(this.width, this.height);
    },
    selectOneAddr(item) {
      this.centerPoint = item.point;
      this.zoom = 14;

      // this.searchResult.forEach((it) => {
      //   if (it.id === item.id) {
      //     it.isCheck = !it.isCheck;
      //   } else {
      //     it.isCheck = false;
      //   }
      // });
    },
    async seachBtn() {
      if (!this.keyword) {
        this.$message.warning("请输入");
        return;
      }
      const res = await axios.get("https://restapi.amap.com/v3/place/text", {
        params: {
          key: "7ca4b62f4a4be50ac2cc92b323dded40",
          keywords: this.keyword,
        },
      });
      if (res.data.infocode === "10000") {
        this.searchResult = res.data.pois.map((item) => ({
          id: item.id,
          addr: item.name,
          detailaddr: item.address,
          point: item.location.split(","),
          isCheck: false,
        })).splice(0, 10);
      }else{
        this.searchResult = []
      }
    },
  },
  mounted() {
    this.initScreensize();
  },
};
</script>

<style lang="less">
.addr-hand-check-win {
  /* width: 1532px; */
  .amap-icon {
    img {
      width: 30px;
      height: auto;
    }
  }
  .amap-overlay-text-container {
    color: #fff;
    background-color: transparent;
    border: none;
  }
  .wrapper {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .top {
      font-size: 12px;
      background-color: #fff;
      margin-bottom: 10px;
    }
    .content {
      position: relative;
      width: 100%;
      height: 100%;
      .map {
        width: 100%;
        background-color: #f4f4f4;
        height: 100%;
      }
      .left_search {
        position: absolute;
        top: 0;
        left: 0;
        width: 280px;
        height: 100%;
        background-color: transparent;
        // border-right: 1px solid #ececec;
        padding: 10px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        .search-inp {
          background-color: #fff;
          .el-input-group__append {
            overflow: hidden;
            padding: 5px 10px;
            .el-button--default {
              background-color: #108ee9;
              color: #fff;
            }
          }
        }
        .search_list {
          background-color: #fff;
          padding: 10px;
          height: 100%;
          .search_title {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
          }
          .search_item {
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 5px;
            box-sizing: border-box;
            .i_left {
              display: flex;
              justify-content: center;
              align-items: center;
              position: relative;
              width: 24px;
              height: 24px;
              img {
                width: 100%;
                height: 100%;
                position: absolute;
                top: 0;
                left: 0;
              }
              .rank {
                color: #ffffff;
                z-index: 99;
              }
            }
            .i_center {
              display: flex;
              align-items: flex-start;
              flex-direction: column;
              flex: 1;
              margin-left: 5px;
              font-size: 14px;
              .c_name {
                font-size: 12px;
                font-weight: bold;
                width: 140px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
              .c_detail {
                margin-top: 4px;
                font-size: 10px;
                color: #999;
                width: 140px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              }
            }
            .i_right {
              padding: 3px 10px;
            }
            &.search_item_on {
              background-color: rgba(16, 142, 233, 0.06);
            }
          }
        }
      }
    }
  }
}

.addr-hand-check-win .el-dialog__title {
  font-size: 14px;
  font-weight: 600;
}
.addr-hand-check-win .el-dialog__header {
  border-bottom: #ececec 1px solid;
  padding: 10px 20px;
}

.addr-hand-check-win .el-dialog__body {
  padding: 20px;
}


.parentdiv_cls{
  padding: 20px 20px 10px 20px;
}
.parentdiv_cls div{
  font-size: 13px;
  color: #444;
  line-height: 22px;

}
.choose_btn_cls{
  background-color: #409EFF;
  border: none;
  color: #fff;
  padding: 5px 15px;
  border-radius: 4px;
  margin-top: 10px;
  cursor: pointer;
  font-size: 13px;
}
.messageBox{
  z-index: 3000 !important;
}
</style>